<template>

  <div class="dashboard">
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ sightTotal }}</div>
            <div class="stat-label">景点总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ articleTotal }}</div>
            <div class="stat-label">文章总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ userTotal }}</div>
            <div class="stat-label">用户总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ orderTotal }}</div>
            <div class="stat-label">订单总数</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="charts-row">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>月度订单统计</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="chartRef" style="width: 100%; height: 400px;"></div>
            
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热门景点排行</span>
            </div>
          </template>
          <div class="ranking-list">
            <div class="ranking-item" v-for="(sight, index) in hotSights" :key="sight.id">
              <span class="ranking-index">{{ index + 1 }}</span>
              <span class="ranking-name">{{ sight.name }}</span>
              <span class="ranking-value">{{ sight.favoriteCount }} 收藏</span>
              <span class="ranking-value">{{ sight.rating }} 分</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="recent-data-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%" size="small">
            <el-table-column prop="id" label="订单号" width="100"></el-table-column>
            <el-table-column prop="user" label="用户" width="100"></el-table-column>
            <el-table-column prop="date" label="日期" width="120"></el-table-column>
            <el-table-column prop="amount" label="金额" width="80"></el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag 
                  :type="{
                    '已完成': 'success',
                    '已付款': 'primary',
                    '待付款': 'warning',
                    '已取消': 'danger',
                    '已退款': 'info'
                  }[scope.row.status] || 'default'"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>新增用户</span>
            </div>
          </template>
          <el-table :data="newUsers" style="width: 100%" size="small">
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="name" label="用户名" width="120"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="date" label="注册日期" width="120"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import { ElMessage } from 'element-plus';
import api from '../services/api';
import * as echarts from 'echarts';
import { getTotalSights, getHotSights } from './api/sight';
import { getTotalArticles } from './api/article';

const router = useRouter();
const authStore = useAuthStore();

// 用户总数
const userTotal = ref(0);

// 订单总数
const orderTotal = ref(0);

// 景点总数
const sightTotal = ref(0);

// 文章总数
const articleTotal = ref(0);

// 热门景点数据
const hotSights = ref([]);

// 获取用户总数
const getUserTotal = async () => {
  try {
    const response = await api.get('/user/total');
    if (response.data && response.data.total !== undefined) {
      userTotal.value = response.data.total;
    }
  } catch (error) {
    console.error('获取用户总数失败:', error);
    ElMessage.error('获取用户总数失败');
  }
};

// 获取订单总数
const getOrderTotal = async () => {
  try {
    const response = await api.get('/order/stats');
    if (response.data.code === 200 ) {
      orderTotal.value = response.data.data.total;
    }
  } catch (error) {
    console.error('获取订单总数失败:', error);
    ElMessage.error('获取订单总数失败');
  }
};

// 获取景点总数
const getSightTotal = async () => {
  try {
    const response = await getTotalSights();
    if (response.data.status === 'success' ) {
      sightTotal.value = response.data.data.count;
      console.log('获取景点总数:', sightTotal.value);
    }
  } catch (error) {
    console.error('获取景点总数失败:', error);
    ElMessage.error('获取景点总数失败');
  }
};

// 最新订单数据
const recentOrders = ref([]);

// 获取最新订单数据
const getRecentOrders = async () => {
  try {
    const response = await api.get('/order/latest/order');
    
    // 检查响应数据格式是否符合预期
    if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
      // 处理字段映射，确保正确匹配后端返回的字段名
      recentOrders.value = response.data.data.map(order => ({
        id: `ORD${order.orderId.toString().padStart(4, '0')}`, // 格式化为ORD0011这样的订单号
        user: `用户${order.userId}`, // 使用用户ID作为用户标识
        date: new Date(order.createdAt).toLocaleDateString('zh-CN'),
        amount: `¥${order.totalPrice}`,
        status: mapOrderStatus(order.status) // 映射订单状态为中文
      }));
      console.log('成功获取最新订单数据:', recentOrders.value);
    } else {
      console.warn('获取最新订单数据格式不符合预期', response.data);
      ElMessage.warning('获取最新订单数据格式异常');
    }
  } catch (error) {
    console.error('获取最新订单失败:', error);
    ElMessage.error('获取最新订单失败: ' + 
      (error.response?.data?.message || 
       error.response?.statusText || 
       error.message || 
       '未知错误'));
  }
};

// 订单状态映射函数
const mapOrderStatus = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '已付款',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  };
  return statusMap[status] || status;
};

// 新增用户数据
const newUsers = ref([
]);

// 月订单统计数据
const monthlyStats = ref([]);

// 图表数据
const chartData = ref({
  dates: [],
  sales: [],
  orders: []
});

// 获取月订单统计数据
const getMonthlyStats = async () => {
  try {
    const response = await api.get('/order/monthly/stats');
    if (response.data && response.data.code === 200 && response.data.data) {
      monthlyStats.value = response.data.data;
      processChartData();
      console.log('成功获取月订单统计数据:', monthlyStats.value);
    } else {
      console.warn('获取月订单统计数据格式不符合预期', response.data);
      ElMessage.warning('获取月订单统计数据格式异常');
    }
  } catch (error) {
    console.error('获取月订单统计失败:', error);
    ElMessage.error('获取月订单统计失败: ' + 
      (error.response?.data?.message || 
       error.response?.statusText || 
       error.message || 
       '未知错误'));
    
    // 提供模拟数据以便查看图表效果
    monthlyStats.value = generateMockData();
    processChartData();
  }
};

// 生成模拟数据
const generateMockData = () => {
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth();
  const currentYear = currentDate.getFullYear();
  
  // 生成符合后端返回格式的模拟数据
  return {
    totalOrders: 11,
    totalSales: 2088,
    completedOrders: 0,
    pendingOrders: 8,
    paidOrders: 2,
    canceledOrders: 1,
    dailyStats: [
      { date: `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`, orders: 11, sales: 2088 }
    ],
    orders: []
  };
};

// 获取文章总数
const getArticleTotal = async () => {
  try {
    const response = await getTotalArticles();
    if (response.data.status === 'success' && response.data.data) {
      articleTotal.value = response.data.data.total;
      console.log('获取文章总数:', articleTotal.value);
    }
  } catch (error) {
    console.error('获取文章总数失败:', error);
    ElMessage.error('获取文章总数失败');
  }
};

// 获取热门景点数据
const getHotSightsData = async () => {
  try {
    const response = await getHotSights();
    if (response.data.status === 'success' && Array.isArray(response.data.data)) {
      hotSights.value = response.data.data;
      console.log('获取热门景点数据:', hotSights.value);
    }
  } catch (error) {
    console.error('获取热门景点数据失败:', error);
    ElMessage.error('获取热门景点数据失败');
    // 提供模拟数据以便查看效果
    hotSights.value = [
      { id: 1, name: '故宫博物院', visits: 2500, rating: '4.8' },
      { id: 2, name: '颐和园', visits: 1800, rating: '4.6' },
      { id: 3, name: '天坛公园', visits: 1200, rating: '4.5' },
      { id: 4, name: '八达岭长城', visits: 2200, rating: '4.7' },
      { id: 5, name: '圆明园遗址公园', visits: 900, rating: '4.3' }
    ];
  }
};

// 处理图表数据
const processChartData = () => {
  if (!monthlyStats.value) return;
  
  // 直接使用后端返回的dailyStats数据
  if (Array.isArray(monthlyStats.value.dailyStats)) {
    const dailyStats = monthlyStats.value.dailyStats;
    
    // 转换为数组并排序
    const sortedData = [...dailyStats].sort((a, b) => {
      return new Date(a.date) - new Date(b.date);
    });
    
    // 更新图表数据
    chartData.value.dates = sortedData.map(item => {
      const date = new Date(item.date);
      return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    });
    chartData.value.sales = sortedData.map(item => Math.round(item.sales));
    chartData.value.orders = sortedData.map(item => item.orders);
  }
};

const handleLogout = () => {
  authStore.logout();
  ElMessage.success('已登出');
  // 重定向到登录页
  router.push('/login');
};

// 获取新增用户数据
const getNewUsers = async () => {
  try {
    const response = await api.get('/user/new');
    
    // 检查响应数据格式是否符合预期
    if (response.data && response.data.message === '查询成功' && Array.isArray(response.data.data)) {
      // 处理字段映射，确保正确匹配后端返回的字段名
      newUsers.value = response.data.data.map(user => ({
        id: user.userId || '',
        name: user.username || '',
        email: user.email || '',
        date: user.createdAt ? new Date(user.createdAt).toLocaleDateString('zh-CN') : ''
      }));
      console.log('成功获取新增用户数据:', newUsers.value);
    } else {
      console.warn('获取新增用户数据格式不符合预期', response.data);
      ElMessage.warning('获取新增用户数据格式异常');
    }
  } catch (error) {
    console.error('获取新增用户失败:', error);
    ElMessage.error('获取新增用户失败: ' + 
      (error.response?.data?.message || 
       error.response?.statusText || 
       error.message || 
       '未知错误'));
    // 保留模拟数据作为备用
  }
};

// 图表相关
const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
  if (chartRef.value && !chartInstance) {
    chartInstance = echarts.init(chartRef.value);
    updateChart();
  }
};

// 更新图表
const updateChart = () => {
  if (!chartInstance) return;
  
  const option = {
    title: {
      text: '本月订单与销售额统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['订单数量', '销售额(元)'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.dates,
      axisLabel: {
        rotate: 45,
        interval: 1
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '销售额(元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '订单数量',
        type: 'bar',
        data: chartData.value.orders,
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '销售额(元)',
        type: 'line',
        yAxisIndex: 1,
        data: chartData.value.sales,
        itemStyle: {
          color: '#91cc75'
        },
        smooth: true,
        lineStyle: {
          width: 3
        }
      }
    ]
  };
  
  chartInstance.setOption(option);
};

// 监听图表数据变化
watch(chartData, () => {
  updateChart();
}, { deep: true });

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 组件挂载时获取数据
onMounted(() => {
  getUserTotal();
  getOrderTotal();
  getSightTotal();
  getArticleTotal();
  getNewUsers();
  getRecentOrders();
  getMonthlyStats();
  getHotSightsData();
  
  // 等待DOM渲染完成后初始化图表
  setTimeout(() => {
    initChart();
    window.addEventListener('resize', handleResize);
  }, 100);
});

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-content {
  text-align: center;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-container {
  height: 480px;
  display: flex;
  flex-direction: column;
}

.placeholder-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 16px;
}

.monthly-stats-container {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-top: 10px;
}

.stats-info {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.table-container {
  height: 300px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ranking-list {
  padding: 10px;
}

.ranking-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.ranking-number {
  width: 24px;
  height: 24px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}

.recent-data-row .el-card {
  margin-bottom: 20px;
}
</style>